package com.qf.controller;

import cn.dsna.util.images.ValidateCode;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.qf.config.KaptchaConfig;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;

@Controller
@RequestMapping("/code")
public class CodeController {

    @RequestMapping("getCode")
    public void getCode(HttpServletRequest  req, HttpServletResponse resp) throws IOException {
        //获取验证码
        ValidateCode validateCode = new ValidateCode(120, 30, 2, 20);

        //在session中存储
        HttpSession session = req.getSession();
        session.setAttribute("code",validateCode.getCode());

        //输出
        validateCode.write(resp.getOutputStream());
    }

    @RequestMapping("/checkCode")
    public void checkCode(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String inputCode = req.getParameter("code");
        //输出
        PrintWriter writer = resp.getWriter();
        //从session中获取验证码
        Object codeObj = req.getSession().getAttribute("code");

        if (codeObj == null){
            writer.write("1");
        }else {
            String code = (String) codeObj;
            if (code.equalsIgnoreCase(inputCode)){
                writer.write("0");
            }else {
                writer.write("1");
            }
        }
    }
}
